const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.showLoading({
      title: '加载中...',
      mask:true
    })
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        setTimeout(function () {
          wx.hideLoading();
        }, 300)
        if (res.statusCode == 200) {
          resolve(res.data);
        } else if (res.statusCode == 401) {
          // 清除登录相关内容
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('token');
          wx.showToast({
            title: '页面过期，请重新登录',
            icon: 'none',
            duration: 1500,
            success: function () {
       
              var pages = getCurrentPages()
              console.log("-------------------------");
              console.log(pages);
              console.log("-------------------------");
              setTimeout(function () {
                //要延时执行的代码
                wx.removeStorageSync('token');
                wx.navigateTo({
                  url: '/pages/auth/accountLogin/accountLogin'
                });
              }, 1000) //延迟时间
            },
          });
        } else {
          wx.hideLoading();
          //系统错误
          reject(res.errMsg);
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/assets/images/icon_error.png'
  })
}

function isNullOrEmpty(obj) {
  if(obj == '' || obj == null || obj == undefined){
    return true;
  }else{
    return false;
  }
}

module.exports = {
  formatTime,
  request,
  showErrorToast,
  isNullOrEmpty
}
